package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
//    https://blog.csdn.net/shengshenglalalala/article/details/100576106

    @Autowired
    private UserService userService;

    @RequestMapping("getUser")
    public User getuser() {
        return userService.Sel("2");
    }

    @RequestMapping("all")
    public List<User> all() {
        List<User> users = userService.queryList();
        return users;
    }

    //查询一条记录
    @RequestMapping("/get_one")
    public User one(HttpServletRequest request) {
        String id = request.getParameter("id");
        User sel = userService.Sel(id);
        return sel;
    }

    // 新增一条记录
    @RequestMapping("addOne")
    public Map addOne(HttpServletRequest request) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
//        if (null == name) {
//            return "缺少用户名" + name;
//        }
//        if (null == password) {
//            return "缺少密码" + password;
//        }
//        if (null == phone) {
//            return "缺少手机号" + phone;
//        }
//        if (null == email) {
//            return "缺少邮箱" + email;
//        }
        Map map = new HashMap();
        map.put("name", request.getParameter("name"));
        map.put("password", request.getParameter("password"));
        map.put("phone", request.getParameter("phone"));
        map.put("email", request.getParameter("email"));
        userService.addOne(map);
        return map;

    }

    // 修改数据
    @RequestMapping("update")
    public String update(User user) {
        int res = userService.update(user);
        if (res >= 1) {
            return "修改成功";
        } else {
            return "修改失败";
        }
    }

    @RequestMapping("del")
    public String del(int id) {
        int res = userService.del(id);
        if (res >= 1) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }
}
